'use client'

import { useState } from 'react'
import { useForm, useFieldArray } from 'react-hook-form'
import { FormInput, FormSelect } from '@/components/ui/form'
import { PlusIcon, TrashIcon } from '@heroicons/react/24/outline'
import { createSale } from '@/actions/sale'
import { useRouter } from 'next/navigation'

interface CreateSaleFormProps {
  products: any[] // 使用序列化后的类型
}

interface SaleFormData {
  items: {
    productId: string
    quantity: string
    price: string
  }[]
}

export function CreateSaleForm({ products }: CreateSaleFormProps) {
  const router = useRouter()
  const [submitting, setSubmitting] = useState(false)
  const [total, setTotal] = useState(0)

  const { register, control, handleSubmit, watch, setValue, formState: { errors } } = useForm<SaleFormData>({
    defaultValues: {
      items: [{ productId: '', quantity: '', price: '' }]
    }
  })

  const { fields, append, remove } = useFieldArray({
    control,
    name: "items"
  })

  // 监听表单变化以计算总金额
  const items = watch('items')
  const calculateTotal = () => {
    const total = items.reduce((sum, item) => {
      if (item.quantity && item.price) {
        return sum + parseFloat(item.quantity) * parseFloat(item.price)
      }
      return sum
    }, 0)
    setTotal(total)
  }

  // 当选择商品时自动填充价格
  const handleProductChange = (index: number, productId: string) => {
    const product = products.find(p => p.id.toString() === productId)
    if (product) {
      setValue(`items.${index}.price`, product.price)
      calculateTotal()
    }
  }

  const onSubmit = async (data: SaleFormData) => {
    try {
      setSubmitting(true)
      const result = await createSale(data)
      if (result.success) {
        router.push('/dashboard/sales/records')
        router.refresh() // 刷新页面数据
      } else {
        alert(result.error)
      }
    } catch (error) {
      console.error('创建销售单失败:', error)
      alert('创建销售单失败')
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <form onSubmit={handleSubmit(onSubmit)} className="space-y-6 p-6">
      {/* 商品列表 */}
      <div className="space-y-4">
        <div className="flex justify-between items-center">
          <h4 className="text-sm font-medium text-gray-700">商品列表</h4>
          <button
            type="button"
            onClick={() => append({ productId: '', quantity: '', price: '' })}
            className="inline-flex items-center text-sm font-medium text-blue-600 hover:text-blue-500"
          >
            <PlusIcon className="h-4 w-4 mr-1" />
            添加商品
          </button>
        </div>

        {fields.map((field, index) => (
          <div key={field.id} className="flex gap-4 items-start">
            <div className="flex-1">
              <FormSelect
                label="商品"
                error={errors.items?.[index]?.productId?.message}
                {...register(`items.${index}.productId`, { 
                  required: '请选择商品',
                  onChange: (e) => handleProductChange(index, e.target.value)
                })}
              >
                <option value="">请选择商品</option>
                {products.map((product) => (
                  <option key={product.id} value={product.id}>
                    {product.name} (库存: {product.stock})
                  </option>
                ))}
              </FormSelect>
            </div>
            <div className="w-32">
              <FormInput
                type="number"
                label="数量"
                error={errors.items?.[index]?.quantity?.message}
                {...register(`items.${index}.quantity`, { 
                  required: '请输入数量',
                  min: { value: 1, message: '数量必须大于0' },
                  onChange: calculateTotal
                })}
              />
            </div>
            <div className="w-32">
              <FormInput
                type="number"
                label="单价"
                error={errors.items?.[index]?.price?.message}
                {...register(`items.${index}.price`, { 
                  required: '请输入单价',
                  min: { value: 0, message: '单价必须大于等于0' },
                  onChange: calculateTotal
                })}
              />
            </div>
            <button
              type="button"
              onClick={() => remove(index)}
              className="mt-8 text-gray-400 hover:text-red-500"
            >
              <TrashIcon className="h-5 w-5" />
            </button>
          </div>
        ))}
      </div>

      {/* 总金额 */}
      <div className="flex justify-end items-center space-x-4">
        <span className="text-lg font-medium text-gray-900">
          总金额：¥{total.toFixed(2)}
        </span>
      </div>

      {/* 按钮 */}
      <div className="flex justify-end gap-4">
        <button
          type="button"
          onClick={() => router.back()}
          className="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50"
        >
          取消
        </button>
        <button
          type="submit"
          disabled={submitting}
          className="px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-md hover:bg-blue-700 disabled:opacity-50"
        >
          {submitting ? '提交中...' : '提交'}
        </button>
      </div>
    </form>
  )
} 